import {
  PROBE_REALTIME
} from '../util/const'

export function pullUpMixin (GScroll) {
  GScroll.prototype._initPullUp = function () {
    // 定时器实时监听滑动
    this.probe = PROBE_REALTIME
    this.pullUpWatching = false
    this._watchPullUp()
  }

  GScroll.prototype._watchPullUp = function () {
    if (this.pullUpWatching) {
      return
    }
    this.pullUpWatching = true
    this.on('scroll', this._checkToEnd)
  }

  GScroll.prototype._checkToEnd = function (pos) {
    const {
      threshold = 0
    } = this.options.pullUpLoad

    // 上拉方向才执行
    if (this.y < 0 && pos.y <= this.maxScrollY + threshold) {
      // 重置上拉加载滚动状态
      this.once('scrollEnd', () => {
        this.pullUpWatching = false
      })
      this.trigger('pullingUp')
      this.off('scroll', this._checkToEnd)
    }
  }

  GScroll.prototype.finishPullUp = function () {
    if (this.pullUpWatching) {
      this.once('scrollEnd', () => {
        this._watchPullUp()
      })
    } else {
      this._watchPullUp()
    }
    this.resetPosition()
  }

  GScroll.prototype.openPullUp = function (config = true) {
    this.options.pullUpLoad = config
    this._initPullUp()
  }

  GScroll.prototype.closePullUp = function () {
    this.options.pullUpLoad = false
    if (!this.pullUpWatching) {
      return
    }
    this.pullUpWatching = false
    this.off('scroll', this._checkToEnd)
  }
}
